import ujson
from window import *
from questionWindow import *
from util import display

class StrInputBox:
	def __init__(self,value,cx,cy,w=2,h=12):
		self.cx = cx
		self.cy = cy
		self.w = w
		self.h = h
		self.focus = 0

		self.value = value
		self.CHARS = "0123456789abcdef"
		self.charInd = self.CHARS.index(self.value)
		
		self.cb_idle = None
		self.cb_click = None
		self.cb_hold = self.increase
		self.cb_holding = self.increase
		self.cb_release = None
	
	def draw(self):
		display.text(self.value,self.cx-self.w//2,self.cy-self.h//2,1)
		if self.focus == 1:
			display.line(self.cx-self.w//2,self.cy+self.h//2,self.cx+self.w//2+4,self.cy+self.h//2,1)
	
	def increase(self):
		self.charInd = (self.charInd + 1) % 16 
		self.value = self.CHARS[self.charInd]


class SetStrWindow(Window):
	def __init__(self,name="Value",tag="essid",default=""):
		Window.__init__(self,250)
		self.name = name
		self.value = default
		self.tag = tag
		self.head = ""

		if self.tag=="essid":
			self.head = self.value[0:3]
			self.value = self.value[3:]
		else:
			self.ib7 = StrInputBox(self.value[6],100,26)
			self.ib8 = StrInputBox(self.value[7],110,26)
		
		# add your component
		self.ib1 = StrInputBox(self.value[0],40,26)
		self.ib2 = StrInputBox(self.value[1],50,26)
		self.ib3 = StrInputBox(self.value[2],60,26)
		self.ib4 = StrInputBox(self.value[3],70,26)
		self.ib5 = StrInputBox(self.value[4],80,26)
		self.ib6 = StrInputBox(self.value[5],90,26)
		self.btn_ok = Button("OK",64,50,35,12)

		Window.add(self,self.ib1)
		Window.add(self,self.ib2)
		Window.add(self,self.ib3)
		Window.add(self,self.ib4)
		Window.add(self,self.ib5)
		Window.add(self,self.ib6)
		if self.tag=="passwd":
			Window.add(self,self.ib7)
			Window.add(self,self.ib8)
		Window.add(self,self.btn_ok)

		# add backgound draw
		Window.setDrawCB(self,self.cb_draw)

		# add your callback
		self.btn_ok.cb_hold = self.cb_ok

	def run(self):
		Window.run(self)
	
	def cb_ok(self):
		if self.tag=="essid":
			self.value = self.head+self.ib1.value+self.ib2.value+self.ib3.value+self.ib4.value+self.ib5.value+self.ib6.value
		else:
			self.value = self.ib1.value+self.ib2.value+self.ib3.value+self.ib4.value+self.ib5.value+self.ib6.value+self.ib7.value+self.ib8.value
		Window.close(self)
	
	def cb_draw(self):
		if self.tag=="essid":
			display.text(self.head,10,20,1)
		display.text(self.name,40,0,1)
